import { useImmer } from 'use-immer'

export const useTableCheck = () => {
  const [selectedRowKeys, setselectedRowKeys] = useImmer<any[]>([])
  const [selectedData, setselectedData] = useImmer<any[]>([])
  const rowSelection = {
    onSelect: (record: any, selected: boolean) => {
      if (selected) {
        setselectedRowKeys((prevState) => {
          prevState.push(record.id)
        })
        setselectedData((prevState) => {
          prevState.push(record)
        })
      } else {
        setselectedRowKeys((prevState) => {
          const index = prevState.findIndex((ele) => ele === record.id)
          prevState.splice(index, 1)
        })
        setselectedData((prevState) => {
          const index = prevState.findIndex((ele) => ele.id === record.id)
          prevState.splice(index, 1)
        })
      }
    },
    onSelectAll: (selected: boolean, _selectedRows: any[], changeRows: any[]) => {
      if (selected) {
        setselectedRowKeys((prevState) => {
          const ids = changeRows.map((item: any) => item.id)
          prevState = [...prevState, ...ids]
          return prevState
        })
        setselectedData((prevState) => {
          prevState = [...prevState, ...changeRows]
          return prevState
        })
      } else {
        setselectedRowKeys((prevState) => {
          const ids = changeRows.map((item: any) => item.id)
          ids.forEach((item: string) => {
            const index = prevState.findIndex((ele) => ele === item)
            prevState.splice(index, 1)
          })
        })
        setselectedData((prevState) => {
          changeRows.forEach((ele: any) => {
            const index = prevState.findIndex((item) => item.id === ele.id)
            prevState.splice(index, 1)
          })
        })
      }
    }
  }

  return {
    selectedRowKeys,
    setselectedRowKeys,
    selectedData,
    setselectedData,
    rowSelection
  }
}
